package com.lyy.blog.web;

import com.lyy.blog.po.comment;
import com.lyy.blog.po.user;
import com.lyy.blog.service.CommentService;
import com.lyy.blog.service.blogservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class CommentController {


    @Autowired
    private CommentService commentService;


    @Autowired
    private blogservice   blogservice;

    @Value("${comment.avatar}")
    private String avatar;
    //把 blogid 拿到
    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model) {
        model.addAttribute("comments", commentService.listCommentByBlogId(blogId));
        return "blog :: commentList";
    }


    @PostMapping("/comments")
    public String post(comment comment, HttpSession session) {
        Long blogId = comment.getBlog().getId();
        comment.setBlog(blogservice.getblog(blogId));
        user user = (user) session.getAttribute("user");
        //判断管理员是否登录，登录了管理员就用自己的头像
        if (user != null) {
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        } else {
            comment.setAvatar(avatar);
        }
        commentService.saveComment(comment);
        return "redirect:/comments/" + blogId;
    }

}
